<?php

namespace Proj\ResManBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Proj\ResmanBundle\Helper\GenerationHelper;


use Proj\ResManBundle\Entity\Resources;
use Proj\ResManBundle\Entity\Person;
use Proj\ResManBundle\Form\ResourcesType;
use Proj\ResManBundle\Form\PersonsType;
use Proj\ResManBundle\Form\RoomType;

/**
 * @Route("/admin")
 */
class AdminController extends Controller{
 
//    function cmp($a, $b)
//    {
//        if ($a->getAmount() > $b->getAmount())
//            return 1;
//        else if ($a->getAmount() < $b->getAmount())
//            return -1;
//        else 
//            return 0;
//    }

    /**
     * @Route("/finance", name="admin_finance")
     */
    public function financeAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $finances = $em->getRepository('ProjResManBundle:Resources')->findBy(array('type' => 0));
        //usort($finances, array($this,'cmp'));
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Admin:finance.html.twig',
            array('finances' => $finances,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
    /**
     * @Route("/finance/add", name="admin_finance_add")
     */
    public function financeAddAction() {
        $resource = new Resources();
        $form = $this->createForm(new ResourcesType(), $resource);
        $request = $this->getRequest();
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $resource->setType(0);
                $em->persist($resource);
                $em->flush(); //se introduce efectiv in baza de date
                
                $this->get('session')->getFlashBag()->add('proj-notice', 'Resursa financiara a fost adaugata.');
                
                return $this->redirect($this->generateUrl('admin_finance_add'));
            }
        }
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Admin:finance_add.html.twig',
            array('form' => $form->createView(),
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
    /**
     * @Route("/people", name="admin_people")
     * @Route("/")
     */
    public function peopleAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $people_list = $em->getRepository('ProjResManBundle:Person')->findAll();
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Admin:people.html.twig',
            array('people_list' => $people_list,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
        /**
     * @Route("/people/add", name="admin_people_add")
     */
    public function peopleAddAction(Request $request) {
        $people = new Person();
        $form = $this->createForm(new PersonsType(), $people);
        $request = $this->getRequest();
        $emailError = false;
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
                
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $people_list = $em->getRepository('ProjResManBundle:Person')->findAll();
                foreach ($people_list as $existingPerson){
                    if ($existingPerson->getEmail() == $people->getEmail()){
                        $emailError = true;
                    }
                }
                $people->setCreationDate(new \DateTime());
                $people->setMiddlename("");
                
                if (! $emailError){
                    $em->persist($people);
                    $em->flush();
                
                
                    $this->get('session')->getFlashBag()->add('proj-notice', 'Resursa umana adaugata cu succes.');
                
                    return $this->redirect($this->generateUrl('admin_people_add'));
                }
            }
        }
        
        return $this->render(
            'ProjResManBundle:Admin:people_add.html.twig',
            array('form' => $form->createView(), 
                  'emailError' => $emailError,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
        /**
     * @Route("/matAndEquip", name="admin_mat_equip")
     */
    public function matEquipAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $matEquips = $em->getRepository('ProjResManBundle:Resources')->findBy(array('type' => 1));
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Admin:matAndEquip.html.twig',
            array('matEquips' => $matEquips,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }  
    
        /**
     * @Route("/matAndEquip/add", name="admin_matEquip_add")
     */
    public function matEquipAddAction() {
        $resource = new Resources();
        $form = $this->createForm(new ResourcesType(), $resource);
        $request = $this->getRequest();
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $resource->setType(1);
                $em->persist($resource);
                $em->flush();
                
                $this->get('session')->getFlashBag()->add('proj-notice', 'Resursa logistica a fost adaugata.');
                
                return $this->redirect($this->generateUrl('admin_matEquip_add'));
            }
        }
        
        return $this->render(
            'ProjResManBundle:Admin:matAndEquip_add.html.twig',
            array('form' => $form->createView(),
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
     /**
     * @Route("/rooms", name="admin_rooms")
     */
    public function roomsAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $rooms = $em->getRepository('ProjResManBundle:Resources')->findBy(array('type' => 2));
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Admin:rooms.html.twig',
            array('rooms' => $rooms,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
        /**
     * @Route("/rooms/add", name="admin_room_add")
     */
    public function roomAddAction() {
        $resource = new Resources();
        $form = $this->createForm(new RoomType(), $resource);
        $request = $this->getRequest();
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $resource->setAmount('1');
                $resource->setType(2);
                $em->persist($resource);
                $em->flush();
                
                $this->get('session')->getFlashBag()->add('proj-notice', 'Resursa logistica a fost adaugata.');
                
                return $this->redirect($this->generateUrl('admin_room_add'));
            }
        }
        
        return $this->render(
            'ProjResManBundle:Admin:room_add.html.twig',
            array('form' => $form->createView(),
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
        private function getTemplateContent($baseurl, $content_array) {
        
        $securityContext = $this->container->get('security.context');
        $token = $securityContext->getToken();
        $user = $token->getUser();
        $roles = "";

        $menu = array(
            "public" => "$baseurl/public/index",
            "admin" => "$baseurl/admin/index",
            "director" => "$baseurl/director/index",
            "cadre" => "$baseurl/cadre/index",
            "login" => "$baseurl/login",
            "logout" => "$baseurl/logout",
        );

        $text = array(
            "login" => "Log-in",
            "logout" => "Log-out",
        );

        $auth = array(
            "user" => $user,
            "isAuth" => $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED'),
            "roles" => $roles
        );

        $header_content = array(
            "menu" => $menu,
            "text" => $text
        );

        $template_content = array(
            "header" => $header_content,
            "content" => $content_array,
            "footer" => array(),
            "auth" => $auth
        );
        
        return $template_content;
    }
    
    private function getLinksArray($baseurl){
        return array (
            1 => array("href" => "$baseurl/admin/people", 
                       "title" => "Resurse umane",
                        "title_desc" => "Inregistreaza resurse umane"),
            2 => array("href" => "$baseurl/admin/finance", 
                        "title" => "Resurse financiare",
                        "title_desc" => "Inregistreaza resurse financiare"),
            3 => array("href" => "$baseurl/admin/matAndEquip", 
                        "title" => "Materiale si echipamente",
                        "title_desc" => "Inregistreaza materiale si echipamente"),
            4 => array("href" => "$baseurl/admin/rooms", 
                        "title" => "Sali",
                        "title_desc" => "Inregistreaza sali"),
        );
    }
}